<template>
    <div class="isDialog">
        <div class="ant-card">
            <div class="ant-card-body">
                <!-- 按钮 -->
                <el-space size="default">
                    <el-button type="primary" size="default"
                        v-perm:system:organ:organ_insert="organInsert">添加机构</el-button>
                    <el-button size="default" @click="bathchClick">批量删除</el-button>
                    <el-button size="default" @click="findOrgan()">
                        <el-icon>
                            <RefreshRight />
                        </el-icon>
                        刷新
                    </el-button>
                </el-space>
                <!-- 当前选择+树形 -->
                <div>
                    <el-row :gutter="24" class="ant-alert-info">
                        <el-col :span="1" :offset="0" class="el-col-center">
                            <el-icon color="#1890ff" size="22px">
                                <WarningFilled />
                            </el-icon>
                        </el-col>
                        <el-col :span="3.2" :offset="0">
                            当前选择:
                        </el-col>
                        <el-col span="auto" :offset="0">
                            {{ organ.orgAbr }}
                        </el-col>
                        <el-col :span="2" :offset="0" v-if="organ.orgAbr != null">
                            <el-button type="primary" size="default" @click="empty" link>
                                取消选择
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-tree ref="tree" :data="organTreeData" node-key="id"
                        :props="{ children: 'children', label: 'orgAbr' }" :show-checkbox="true"
                        :highlight-current="true" :default-expand-all='true' :expand-on-click-node="false"
                        @node-click="TreeDataClick" check-strictly>
                    </el-tree>
                </div>
                <div class="line">
                    <div />
                </div>
                <el-dropdown trigger="click" size="default" placement="top" @command="treeOperate">
                    <el-button>
                        树操作
                        <el-icon class="el-icon--right">
                            <ArrowUp />
                        </el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="checkAll">
                                全部勾选
                            </el-dropdown-item>
                            <el-dropdown-item command="uncheckAll">
                                取消勾选
                            </el-dropdown-item>
                            <el-dropdown-item command="expandAll">
                                展开所有
                            </el-dropdown-item>
                            <el-dropdown-item command="mergeAll">
                                合并所有
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>

            <div class="ant-card-body">
                <div v-if="visible">
                    <el-form :model="organClick" ref="formRef" :rules="rules" label-width="80px" :inline="false"
                        size="default" status-icon :validate-on-rule-change="false">
                        <el-form-item label="名称:" prop="orgAbr" required>
                            <el-input v-model="organClick.orgAbr"></el-input>
                        </el-form-item>
                        <el-form-item label="编号:" prop="orgNo" required>
                            <el-input v-model="organClick.orgNo"></el-input>
                        </el-form-item>
                        <el-form-item label="上级机构:" prop="parentId">
                            <el-tree-select v-model="computedParentId" :data="treeSelectData" check-strictly
                                :props="{ children: 'children', label: 'orgAbr', value: 'id' }"
                                :default-expand-all="true" :render-after-expand="false" placeholder="请选择上级机构" clearable>
                            </el-tree-select>
                        </el-form-item>
                        <el-form-item label="排序:" prop="sort">
                            <el-input v-model="organClick.sort"></el-input>
                        </el-form-item>
                        <el-form-item label="备注:" prop="remark">
                            <el-mention type="textarea" v-model="organClick.remark"></el-mention>
                        </el-form-item>
                        <div class="button-container">
                            <el-button @click="reset()">
                                <el-icon>
                                    <Refresh />
                                </el-icon><span>重置</span>
                            </el-button>
                            <el-button type="primary" @Click="onsubmit(formRef)">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                <span>保存</span>
                            </el-button>
                        </div>

                    </el-form>

                </div>
                <div v-else>
                    <el-empty description="请选择一个机构!"></el-empty>
                </div>
            </div>
        </div>

        <el-dialog title="确认删除" v-model="dialogVisible" width="30%" :destroy-on-close="true" draggable>
            <span>确认删除选中的{{ getOrganLength() }}条数据？</span>
            <template #footer>
                <span>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="batchRemove">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog :title="dialogTitle" v-model="dialogVisibleTwo" width="38%" draggable :destroy-on-close="true">
            <router-view @close="close"></router-view>
        </el-dialog>
    </div>



</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage } from "element-plus";
import request from '@/api/request';
import router from '@/router';
let formRef = ref(null);
let tree = ref(null); // 树引用对象
let organTreeData = ref([]) // 树展示数据
let visible = ref(false);
let dialogVisible = ref(false) // 删除
let dialogVisibleTwo = ref(false) // 新增
let dialogTitle = ref('') // 新增标题

let treeSelectData = ref([])

class State {
    id = 0;
    orgNo = null;
    orgAbr = null;
    parentId = 0;
    sort = '';
    remark = '';
    tenantId = 0;
};

let organ = ref(new State())
// 树点击对象/表单对象
let organClick = ref(new State())


const findOrgan = () => {
    request.get('organ/findOrganTree').then(resp => {
        if (resp.code == 200) {
            organTreeData.value = resp.data
        }
    })
}
findOrgan();

/**
 * 点击树节点事件
 * @param item 当前节点对象
 */
const TreeDataClick = (item: any) => {
    organClick.value = { ...item }
    organ.value = { ...item }
    queryParent()
    visible.value = true
};
// 查询树形上级机构
const queryParent = async () => {
    await request.get('organ/queryParent', {
        params: {
            id: organClick.value.id, // 确保传递的参数是后端所需的  
            parentId: organClick.value.parentId
        }
    }).then(resp => {
        if (resp.code == 200) {
            treeSelectData.value = resp.data
        }
    })
};

const rules = reactive({
    orgAbr: [
        { required: true, message: '请输入名称！', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                findOrgOne(value).then(value => {
                    if (value) {
                        callback()
                    } else {
                        callback(new Error("名称已经存在"))
                    }
                })
            }
        }
    ],
    orgNo: [
        { required: true, message: '请输入编号！', trigger: 'blur' }
    ]
})

// 查询单个机构，用于验证机构名是否重复
const findOrgOne = async (orgAbr: String) => {
    const resp = await request.get("organ/findOrgOne", {
        params: {
            orgAbr: orgAbr
        }
    });
    if (resp.code == 200) {
        return resp.data;
    }
}

// 处理无上级的机构显示
const computedParentId = computed({
    get() {
        return organClick.value.parentId === 0 ? null : organClick.value.parentId;
    },
    set(value) {
        organClick.value.parentId = value;
    }
});

const onsubmit = (formEl) => {
    formEl.validate(v => {
        if (v) {
            request.put('organ/upOrgan', { ...organClick.value }).then(resp => {
                if (resp.code == 200) {
                    ElMessage({
                        message: '保存成功！',
                        type: 'success'
                    })
                    organ.value = { ...organClick.value }
                    findOrgan()
                }
            })
        }
    })
};

const reset = () => {
    organClick.value = new State()
};

const bathchClick = () => {
    let nodes = parseInt(getOrganLength());
    if (nodes <= 0) {
        ElMessage({
            message: '请选择至少一条记录！',
            type: 'warning'
        })
    } else {
        dialogVisible.value = true
    }
}

const getOrganLength = () => {
    return tree.value.getCheckedNodes().length;
}

const batchRemove = () => {
    let hasChildren = (node, treeData) => {
        if (!Array.isArray(treeData.value)) {
            return false;
        }
        for (let value of treeData.value) {
            if (value.id === node.id) {
                return value.children && value.children.length > 0;
            }
            if (value.children) {
                let result = hasChildren(node, { value: value.children })
                if (result) return result;
            }
        }
        return false
    }

    let nodes = tree.value.getCheckedNodes()
    let arr = []
    nodes.forEach((value) => {
        arr.push(hasChildren(value, organTreeData))
    });
    if (!arr.find(item => item == true)) {
        console.log(nodes);

        // 获取id
        let organAbs = []
        nodes.forEach(value => {
            organAbs.push(value.orgAbr)
        });
        console.log(organAbs);
        // // 删除操作
        request.delete(`organ/batchRemoveOrgan/${organAbs}`).then(resp => {
            if (resp.code == 200) {
                ElMessage({
                    message: '成功',
                    type: 'success'
                })
                findOrgan();
            }
        })
    } else {
        ElMessage({
            message: '该机构存在下级不允许删除',
            type: 'warning'
        })
    }
    dialogVisible.value = false;
}

const organInsert = (p) => {
    console.log(p);

    dialogTitle.value = p.cname
    router.push(p.path)
    dialogVisibleTwo.value = true
}

const close = () => {
    dialogVisibleTwo.value = false
    findOrgan()
}

// 树操作
let treeOperate = (command: any) => {
    switch (command) {
        case 'checkAll':
            checkAll()
            break;
        case 'uncheckAll':
            uncheckAll()
            break;
        case 'expandAll':
            expandAll()
            break;
        case 'mergeAll':
            mergeAll()
            break;
    }
};

// 全部勾选
let checkAll = () => {
    let ids = []
    let traverse = (node) => {
        if (node && node.id) {
            ids.push(node.id);
        }

        if (node.children && node.children.length) {
            // 递归遍历子节点
            node.children.forEach(child => traverse(child));
        }
    }
    organTreeData.value.forEach(node => traverse(node));
    console.log(ids);
    tree.value.setCheckedKeys(ids, false)
};

// 取消勾选
let uncheckAll = () => {
    tree.value.setCheckedKeys(ref([]).value, false)
};

// 展开所有子项
let expandAll = () => {
    const nodes = tree.value.store._getAllNodes();
    nodes.forEach((item: { expanded: boolean; }) => {
        item.expanded = true;
    });
};
// 合并所有
let mergeAll = () => {
    const nodes = tree.value.store._getAllNodes();
    nodes.forEach((item: { expanded: boolean; }) => {
        item.expanded = false;
    });
};

const empty = () => {
    organ.value = new State()
    visible.value = false
};
</script>

<style scoped>
.ant-card {
    display: flex;
    /* 子元素间距相等 */
    justify-content: space-evenly;
    /* 子元素高度互不影响 */
    align-items: flex-start;
    /* flex-shrink: 0; */
}

.ant-card-body {
    background-color: white;
    padding: 24px !important;
    display: inline-block;
    width: 45%;
}

.ant-alert-info {
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    padding: 6px 10px;
    border-radius: 4px;
    margin-top: 10px;
    line-height: 1.5;
}

.el-col-center {
    display: flex;
}

.el-tree {
    margin-top: 10px;
}

.line div {
    height: 0;
    border-top: 1px solid var(--el-border-color);
    margin: 30px 0 10px 0;
}

.justufy-center .el-form-item__content {
    display: flex;
    justify-content: center;
}
</style>
